(() => {
  class Settings {
    constructor($exception) {
      this.exception = $exception;
    }
    post (task) {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('task', (result) => {
          if (result && Object.keys(result).length) {
            reject({
              status: 409,
              statusText: '任务已存在' 
            });
          }
          else {
            if (!task.created) {
              task.created = Date.now();
            }
            task.modified = Date.now();
            chrome.storage.local.set({'task': task}, () => {
              resolve({
                status: 200,
                statusText: '任务已保存'
              })
            })
          }
        })
      });
    }
    delete () {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('task', (result) => {
          if (result && Object.keys(result).length) {
            resolve({
              status: 204,
              statusText: '任务不存在' 
            });
          }
          else {
            chrome.storage.local.remove('task', () => {
              resolve({
                status: 200,
                statusText: '任务已删除'
              })
            })
          }
        })
      });
    }
    put (task) {
      return new Promise((resolve, reject) => {
        if (!task || !Object.keys(task).length) {
          reject({
            status: 406,
            statusText: '任务不能为空'
          });
        }
        else {
          if (!task.created) {
            task.created = Date.now();
          }
          task.modified = Date.now();
          chrome.storage.local.set({'task': task}, (result) => {
            resolve({
              status: 200,
              statusText: '任务已保存'
            })
          })
        }
      });
    }
    get () {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('task', (result) => {
          if (result && Object.keys(result).length) {
            resolve({
              status: 200,
              statusText: 'OK',
              response: result.task
            });
          }
          else {
            reject({
              status: 404,
              statusText: '任务不存在',
              response: null
            })
          }
        })
      });
    }
  }
  angular.module('app').factory('$task', ['$exception', ($exception) => new Settings($exception)]);
})()